package com.demo.workbook.service.impl;

import com.demo.workbook.entity.MyUser;
import com.demo.workbook.service.MyVerifyPermissionsService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;


/**
 * 自定义权限校验
 */
@Service
public class MyVerifyPermissionsServiceImpl implements MyVerifyPermissionsService {

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {

        Object obj = authentication.getPrincipal();
        if (obj instanceof MyUser) {
            //获取登录用户
            MyUser myUser = (MyUser) authentication.getPrincipal();
            //获取用户的授权
            Collection<? extends GrantedAuthority> authorities = myUser.getAuthorities();

            //实际开发中，从数据库中查询出该请求资源需要的权限
            String permission = request.getRequestURI();

            return authorities.contains(new SimpleGrantedAuthority(permission));
        }

        return false;
    }

}
